package com.kzd.gtgame.main.mine

import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setOnClickAntiShakeListener
import com.kzd.gtgame.custom.setTransitionStatusE
import com.kzd.gtgame.jetpack.vm.AddressViewModel
import com.kzd.gtgame.main.KEY_ADDRESS_INFO
import com.kzd.gtgame.main.mine.adapter.MineAddressAdapter
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_address_list.*
import kotlinx.android.synthetic.main.include_app_refresh.*


class AddressListFragment : OwnerViewModeFragment<AddressViewModel>() {

    companion object {
        fun newInstance(): AddressListFragment {
            return AddressListFragment()
        }
    }

    private val mMineAddressAdapter = MineAddressAdapter()

    override fun viewModel(): AddressViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.fragment_address_list

    override fun initView() {
        rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }.adapter = mMineAddressAdapter

        mMineAddressAdapter.setOnItemClickListener { _, _, position ->
            val itemData = mMineAddressAdapter.getItem(position)
            val intent = Intent().apply {
                putExtra(KEY_ADDRESS_INFO, itemData)
            }
            requireActivity().setResult(1, intent)
            requireActivity().finish()
        }

        mMineAddressAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData = mMineAddressAdapter.getItem(position)
            if (view.id == R.id.ivAddressEdit) {
                viewModel.addressInfoLiveData.postValue(itemData)
            }
        }

        tvAddressAdd.setOnClickAntiShakeListener {
            viewModel.addressInfoLiveData.postValue(null)
        }

        mSmartRefreshLayout.setOnRefreshListener {
            viewModel.userAddress()
        }
    }

    override fun initData() {
        viewModel.userAddress()
    }

    override fun initViewMode() {
        viewModel.userAddressLiveData.observe(viewLifecycleOwner, { response ->
            this.setTransitionStatusE(response, mMineAddressAdapter, mSmartRefreshLayout, (false))
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            mMineAddressAdapter.setNewInstance(data)
        })
    }

}